import React, { forwardRef, useEffect, useState } from "react";
import {
  Dialog as MuiDialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Button,
  Slide,
  Box,
  useTheme,
  alpha,
} from "@mui/material";
import type { TransitionProps } from "@mui/material/transitions";

// 定义过渡动画
const Transition = forwardRef(function Transition(
  props: TransitionProps & {
    children: React.ReactElement;
  },
  ref: React.Ref<unknown>
) {
  return <Slide direction="up" ref={ref} {...props} />;
});

export interface DialogProps {
  title: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
  onConfirm: () => void;
  onCancel: () => void;
  onClose?: () => void; // 设为可选，因为我们现在不使用它
  type?: "warning" | "info" | "error" | "success";
  isOpen: boolean;
  // 新增可选属性
  maxWidth?: "xs" | "sm" | "md" | "lg" | "xl" | false;
  fullWidth?: boolean;
  disableBackdropClick?: boolean;
  disableEscapeKeyDown?: boolean;
}

/**
 * 增强的对话框组件
 *
 * 基于 Material-UI 的 Dialog 组件，提供更现代化的外观和交互体验
 * 支持多种类型：info、success、warning、error
 * 支持亮色/暗色模式自动适配
 * 保持与原有 Dialog 组件相同的接口，方便无缝替换
 * @author BelovedLYC
 */
const Dialog: React.FC<DialogProps> = ({
  title,
  message,
  confirmText = "确认",
  cancelText = "取消",
  onConfirm,
  onCancel,
  type = "info",
  isOpen,
  maxWidth = "sm",
  fullWidth = true,
  disableBackdropClick = false,
  disableEscapeKeyDown = false,
}) => {
  const theme = useTheme();
  const [isDarkMode, setIsDarkMode] = useState(false);

  // 检测当前主题模式
  useEffect(() => {
    const checkDarkMode = () => {
      const isDark = document.documentElement.classList.contains("dark");
      setIsDarkMode(isDark);
    };

    // 初始检查
    checkDarkMode();

    // 创建一个观察器来监听 HTML 元素的 class 变化
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (
          mutation.type === "attributes" &&
          mutation.attributeName === "class"
        ) {
          checkDarkMode();
        }
      });
    });

    // 开始观察
    observer.observe(document.documentElement, { attributes: true });

    // 清理观察器
    return () => observer.disconnect();
  }, []);

  // 处理点击背景关闭
  const handleBackdropClick = () => {
    if (disableBackdropClick) return;
    onCancel();
  };

  // 处理确认按钮点击
  const handleConfirm = () => {
    onConfirm();
  };

  // 处理取消按钮点击
  const handleCancel = () => {
    onCancel();
  };

  // 根据类型获取颜色配置
  const getTypeConfig = () => {
    switch (type) {
      case "warning":
        return {
          color: theme.palette.warning.main,
          lightColor: alpha(theme.palette.warning.main, isDarkMode ? 0.2 : 0.1),
          icon: (
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="currentColor"
              className="w-6 h-6"
            >
              <path
                fillRule="evenodd"
                d="M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z"
                clipRule="evenodd"
              />
            </svg>
          ),
        };
      case "error":
        return {
          color: theme.palette.error.main,
          lightColor: alpha(theme.palette.error.main, isDarkMode ? 0.2 : 0.1),
          icon: (
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="currentColor"
              className="w-6 h-6"
            >
              <path
                fillRule="evenodd"
                d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25zm-1.72 6.97a.75.75 0 10-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 101.06 1.06L12 13.06l1.72 1.72a.75.75 0 101.06-1.06L13.06 12l1.72-1.72a.75.75 0 10-1.06-1.06L12 10.94l-1.72-1.72z"
                clipRule="evenodd"
              />
            </svg>
          ),
        };
      case "success":
        return {
          color: theme.palette.success.main,
          lightColor: alpha(theme.palette.success.main, isDarkMode ? 0.2 : 0.1),
          icon: (
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="currentColor"
              className="w-6 h-6"
            >
              <path
                fillRule="evenodd"
                d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z"
                clipRule="evenodd"
              />
            </svg>
          ),
        };
      default: // info
        return {
          color: theme.palette.info.main,
          lightColor: alpha(theme.palette.info.main, isDarkMode ? 0.2 : 0.1),
          icon: (
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="currentColor"
              className="w-6 h-6"
            >
              <path
                fillRule="evenodd"
                d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm8.706-1.442c1.146-.573 2.437.463 2.126 1.706l-.709 2.836.042-.02a.75.75 0 01.67 1.34l-.04.022c-1.147.573-2.438-.463-2.127-1.706l.71-2.836-.042.02a.75.75 0 11-.671-1.34l.041-.022zM12 9a.75.75 0 100-1.5.75.75 0 000 1.5z"
                clipRule="evenodd"
              />
            </svg>
          ),
        };
    }
  };

  const typeConfig = getTypeConfig();

  return (
    <MuiDialog
      open={isOpen}
      TransitionComponent={Transition}
      onClose={handleBackdropClick}
      maxWidth={maxWidth}
      fullWidth={fullWidth}
      disableEscapeKeyDown={disableEscapeKeyDown}
      PaperProps={{
        sx: {
          borderRadius: 2,
          boxShadow: 3,
          overflow: "visible",
          bgcolor: isDarkMode ? "rgb(17, 24, 39)" : "background.paper",
          color: isDarkMode ? "rgb(243, 244, 246)" : "text.primary",
        },
      }}
    >
      {/* 图标装饰 */}
      <Box
        sx={{
          position: "absolute",
          top: -20,
          left: {
            xs: "calc(50% - 20px)",
            sm: 24,
          },
          width: 40,
          height: 40,
          borderRadius: "50%",
          backgroundColor: typeConfig.lightColor,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: typeConfig.color,
          border: `2px solid ${
            isDarkMode ? "rgb(17, 24, 39)" : theme.palette.background.paper
          }`,
        }}
      >
        {typeConfig.icon}
      </Box>

      {/* 标题 */}
      <DialogTitle
        sx={{
          pt: 3,
          pb: 1,
          px: 3,
          "& .MuiTypography-root": {
            fontSize: "1.25rem",
            fontWeight: 600,
            color: isDarkMode ? "rgb(243, 244, 246)" : "text.primary",
          },
        }}
      >
        {title}
      </DialogTitle>

      {/* 内容 */}
      <DialogContent sx={{ px: 3, py: 2 }}>
        <DialogContentText
          sx={{
            color: isDarkMode ? "rgb(209, 213, 219)" : "text.secondary",
            whiteSpace: "pre-line", // 保留换行符
          }}
        >
          {typeof message !== "string" ? "[非文本内容]" : message}
        </DialogContentText>
      </DialogContent>

      {/* 按钮区 */}
      <DialogActions
        sx={{
          px: 3,
          py: 2,
          justifyContent: "flex-end",
          gap: 1,
        }}
      >
        <Button
          variant="outlined"
          onClick={handleCancel}
          sx={{
            borderRadius: 1.5,
            textTransform: "none",
            fontWeight: 500,
            px: 2,
            borderColor: isDarkMode ? "rgba(209, 213, 219, 0.5)" : undefined,
            color: isDarkMode ? "rgb(209, 213, 219)" : undefined,
            "&:hover": {
              borderColor: isDarkMode ? "rgb(209, 213, 219)" : undefined,
              backgroundColor: isDarkMode
                ? "rgba(255, 255, 255, 0.05)"
                : undefined,
            },
          }}
        >
          {cancelText}
        </Button>
        <Button
          variant="contained"
          onClick={handleConfirm}
          color={type}
          sx={{
            borderRadius: 1.5,
            textTransform: "none",
            fontWeight: 500,
            px: 2,
            boxShadow: 1,
          }}
        >
          {confirmText}
        </Button>
      </DialogActions>
    </MuiDialog>
  );
};

export default Dialog;
